# -*- coding: utf-8 -*-
# @Time    : 2024/1/18 20:59
# @Author  : micah
# @File    : 8.使用python完成爱奇艺数据提取并保存到mongodb.py
# @Software: PyCharm


import pymongo
import requests


class AiQiYi:
    def __init__(self):
        self.mongo_client = pymongo.MongoClient(host='localhost', port=27017)
        self.db = self.mongo_client['py_spider']['AiQiYi']

        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            'Referer': 'https://list.iqiyi.com/www/2/15-------------11-1-1-iqiyi--.html?s_source=PCW_SC'
        }

        self.api_url = 'https://pcw-api.iqiyi.com/search/recommend/list'

    # 获取数据函数
    def get_movie_info(self, params):
        response = requests.get(self.api_url, headers=self.headers, params=params).json()
        return response['data']['list']

    # 解析数据函数
    def parse_movie_info(self, response):
        for movie in response:
            item = dict()
            item['title'] = movie['title']
            item['playUrl'] = movie['playUrl']
            item['description'] = movie['description']
            self.save_movie_info(item)

    # 保存数据函数
    def save_movie_info(self, item):
        self.db.insert_one(item)
        print(f'保存成功: {item}')


if __name__ == '__main__':
    aqy = AiQiYi()

    for page in range(1, 11):
        params_dict = {
            "channel_id": "2",
            "data_type": "1",
            "mode": "11",
            "page_id": str(page),
            "ret_num": "48",
            "session": "3a6d986f3e6ca1ddef49c621aa20918c",
            "three_category_id": "15;must"
        }
        results = aqy.get_movie_info(params_dict)
        aqy.parse_movie_info(results)
